Multiple graphs on one page (ggplot2)
Problem
You want to put multiple graphs on one page.
Solution
The easy way is to use the multiplot
function, defined at the bottom of this page. If it isn't suitable for your needs, you can copy and modify it.
First, set up the plots and store them, but don't render them yet. The details of these plots aren't important; all you need to do is store the plot objects in variables.
library(ggplot2) # This example uses the ChickWeight dataset, which comes with ggplot2 # First plot p1 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) + geom_line() opts(title="Growth curve for individual chicks") # Second plot p2 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet)) + geom_point(alpha=.3) + geom_smooth(alpha=.2, size=1) + opts(title="Fitted growth curve per diet") # Third plot p3 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, colour=Diet)) + geom_density() + opts(title="Final weight, by diet") # Fourth plot p4 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, fill=Diet)) + geom_histogram(colour="black", binwidth=50) + facet_grid(Diet ~ .) + opts(title="Final weight, by diet") + opts(legend.position="none") # No legend (redundant in this graph)
Once the plot objects are set up, we can render them with multiplot
. This will make two columns of graphs:
multiplot(p1, p2, p3, p4, cols=2)
multiplot function
This is the definition of multiplot
. It can take any number of plot objects as arguments, or if it can take a list of plot objects passed to plotlist
.
multiplot <- function(..., plotlist=NULL, cols) { require(grid) # Make a list from the ... arguments and plotlist plots <- c(list(...), plotlist) numPlots = length(plots) # Make the panel plotCols = cols # Number of columns of plots plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols # Set up the page grid.newpage() pushViewport(viewport(layout = grid.layout(plotRows, plotCols))) vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y) # Make each plot, in the correct location for (i in 1:numPlots) { curRow = ceiling(i/plotCols) curCol = (i-1) %% plotCols + 1 print(plots[[i]], vp = vplayout(curRow, curCol )) } }